package com.didispace.chapter11.web
import com.didispace.chapter11.domain.User
import com.didispace.chapter11.service.IUserService
import io.swagger.annotations.Api
import io.swagger.annotations.ApiImplicitParam
import io.swagger.annotations.ApiOperation
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.web.bind.annotation.*
import javax.validation.Valid


/**
 * @author 田桂森 2020/7/22 0022
 */
@Api(tags = ["1-用户管理"])
@RestController
@RequestMapping("/users/")// 通过这里配置使下面的映射都在/users下
class UserController {
    // 创建线程安全的Map，模拟users信息的存储
    @Autowired
    private lateinit var userSerivce: IUserService
    var users: MutableMap<Long, User> = mutableMapOf()

    /**
     * 处理"/users/"的GET请求，用来获取用户列表
     *
     * @return
     */
    @GetMapping("")
    @ApiOperation("获取用户列表")
    fun getUserList(): List<User> {
        return users.values.toList()
    }

    /**
     * 处理"/users/"的POST请求，用来创建User
     *
     * @param user
     * @return
     */
    @PostMapping("")
    @ApiOperation(value = "创建用户", notes = "根据User对象创建用户")
    fun postUser(@Valid @RequestBody user: User): Int { // @RequestBody注解用来绑定通过http请求中application/json类型上传的数据//@Valid校验
        return userSerivce.create(user.name,user.age)
    }

    /**
     * 处理"/users/{id}"的GET请求，用来获取url中id值的User信息
     *
     * @param id
     * @return
     */
    @GetMapping("{id}")
    @ApiImplicitParam(paramType = "path", dataType = "Long", name = "id", value = "用户编号", required = true, example = "1")
    @ApiOperation(value = "获取用户详细信息", notes = "根据url的id来获取用户详细信息")
    fun getUser(@PathVariable id: Long?): User? { // url中的id可通过@PathVariable绑定到函数的参数中
        return users[id]
    }

    /**
     * 处理"/users/{id}"的PUT请求，用来更新User信息
     *
     * @param id
     * @param user
     * @return
     */
    @PutMapping("{id}")
    @ApiImplicitParam(paramType = "path", dataType = "Long", name = "id", value = "用户编号", required = true, example = "1")
    @ApiOperation(value = "更新用户详细信息", notes = "根据url的id来指定更新对象，并根据传过来的user信息来更新用户详细信息")
    fun putUser(@PathVariable id: Long?, @RequestBody user: User): String? {
        val u = users[id]
        u?.name = user.name
        u?.age = user.age
        users[id!!] = u!!
        return "success"
    }

    /**
     * 处理"/users/{id}"的DELETE请求，用来删除User
     *
     * @param id
     * @return
     */
    @DeleteMapping("{id}")
    @ApiOperation(value = "删除用户", notes = "根据url的id来指定删除对象")
    fun deleteUser(@PathVariable id: Long?): String? {
        users.remove(id)
        return "success"
    }

}